//
//  JLYSViewController_detail.m
//  Estate
//
//  Created by heyong on 16/6/23.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "JLYSViewController_detail.h"
#import "TableTopStateCell.h"
#import "B_wuLiaoCell.h"
#import "DefaineCell.h"
#import "FDAlertView.h"
#import "AlertVIew.h"
#import "AttachmentMessageCell.h"
#import "ProcessRecordModel.h"
#import "H1_ImagesCell.h"

@interface JLYSViewController_detail ()
{
    FDAlertView *alert;
    FMDatabase *_db;
    //判断是否合格
    int _qualified;
}
@property (copy, nonatomic) NSString *content;
// 流程记录表模型
@property (nonatomic, strong) ProcessRecordModel *pRecordModel;
// 审阅状态
@property (assign, nonatomic) int reviewState;

@property (strong, nonatomic) Tweet *curTweet;

@property (strong, nonatomic) NSMutableArray *selectedAssetURLs;
// 图片name
@property (strong, nonatomic) NSArray *firstArr;
/**数据源*/
@property (strong ,nonatomic)NSMutableArray *dataArray;

@end

@implementation JLYSViewController_detail

- (NSMutableArray *)selectedAssetURLs {
    if(!_selectedAssetURLs){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}


- (NSMutableArray *)dataArray{
    if(_dataArray==nil){
        _dataArray=[NSMutableArray array];
    }
    return _dataArray;
}

- (NSArray *)firstArr {
    if (!_firstArr) {
        _firstArr = [[NSArray alloc] init];
    }
    return _firstArr;
}


- (TPKeyboardAvoidingTableView *)tableView{
    if(_tableView==nil){
        _tableView=[[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.bounces=NO;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"TableTopStateCell" bundle:nil] forCellReuseIdentifier:@"topCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"tCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"fCell"];
        [_tableView registerClass:[AttachmentMessageCell class] forCellReuseIdentifier:@"amCell"];
        [_tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:@"photoCell"];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor=[UIColor whiteColor];
    NSLog(@"流程id:%@",self.processId);
    _curTweet = [[Tweet alloc] init];
    self.title=@"验收单";
    _db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
    // 获取数据
    [self setData];
    
    NSLog(@"id:%@",self.dataArray);

    if(self.dataArray.count==0){
        [LSUtility showToastWithMessage:@"数据获取异常。" inView:self.view Andtime:1.8];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        return;
    }else{
        [self.view addSubview:self.tableView];
    }
    
    //状态为待验收
    if (self.dataArray.count == 0) {
        return;
    } else {
        self.pRecordModel = self.dataArray[0];
    }
    
    
    // 获取图片
    self.firstArr = [self getAttachment:self.pRecordModel.FILEINFOS];
    [self getImagePath:self.firstArr];
    
    if(self.pRecordModel.PROCESS_STAGE == PROCESS_STAGE_START || self.pRecordModel.PROCESS_STAGE == PROCESS_STAGE_CHECK){
        [self cteateRightItem];
    }
}

- (void)setData {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    /*
     * 根据日期查询展开的数据
     */
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT *, time(CREATE_TIME), date(CREATE_TIME) FROM PROCESS_RECORD WHERE PROCESS_ID = '%@' ORDER BY CREATE_TIME DESC",self.processId];
    [db open];
    
    FMResultSet *results=[db executeQuery:sqlStr];
    
    while ([results next]) {
        ProcessRecordModel *model=[[ProcessRecordModel alloc]init];
        model.ID=[results stringForColumn:@"ID"];
        model.PRO_ID=[results stringForColumn:@"PRO_ID"];
        model.ADDRESS_ID=[results stringForColumn:@"ADDRESS_ID"];
        model.ADDRES_INFO=[results stringForColumn:@"ADDRES_INFO"];
        model.PROCESS_TYPE=[results intForColumn:@"PROCESS_TYPE"];
        model.PROCESS_STAGE=[results intForColumn:@"PROCESS_STAGE"];
        model.RECORD_USER = [results stringForColumn:@"RECORD_USER"];
        model.RECORD_MASTER=[results stringForColumn:@"RECORD_MASTER"];
        model.RECIFY_USER=[results stringForColumn:@"RECIFY_USER"];
        model.RECIFY_UNIT=[results stringForColumn:@"RECIFY_UNIT"];
        model.SEVERITY=[results stringForColumn:@"SEVERITY"];
        model.END_TIME=[results stringForColumn:@"END_TIME"];
        model.SEND_TYPE=[results intForColumn:@"SEND_TYPE"];
        model.PROCESS_TITLE=[results stringForColumn:@"PROCESS_TITLE"];
        model.PROCESS_CONTENT=[results stringForColumn:@"PROCESS_CONTENT"];
        model.PROCESS_REQUIRED=[results stringForColumn:@"PROCESS_REQUIRED"];
        model.PROCESS_DESC=[results stringForColumn:@"PROCESS_DESC"];
        model.SUBMITTORS=[results stringForColumn:@"SUBMITTORS"];
        model.PUT_USER=[results stringForColumn:@"PUT_USER"];
        model.REVIEW_OPINION=[results stringForColumn:@"REVIEW_OPINION"];
        model.SUBMITTORS=[results stringForColumn:@"SUBMITTORS"];
        model.zhuangtai=[results intForColumn:@"REVIEW_STATE"];
        model.FILEINFOS=[results stringForColumn:@"FILEINFOS"];
        model.EXTEND_INFO=[results stringForColumn:@"EXTEND_INFO"];
        model.CREATE_TIME=[results stringForColumn:@"CREATE_TIME"];
        model.CREATE_DATE=[results stringForColumn:@"date(CREATE_TIME)"];
        [self.dataArray addObject:model];
        break;
    }
    [db close];
}

// 获取数据ExtendInfo
- (NSArray *)getAttachment:(NSString *)fileinfos {
    // JSON转数组
    NSData *fileinfosData = [fileinfos dataUsingEncoding:NSASCIIStringEncoding];
    NSArray *fileinfosArr = [LSUtility toArrayOrNSMutableDictionary:fileinfosData];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    // 查找extendInfo
    NSMutableArray *AttArr = [NSMutableArray array];
    for (int i = 0; i < fileinfosArr.count; i++) {
        NSDictionary *fileinfosDic = fileinfosArr[i];
        NSString *sql = [NSString stringWithFormat:@"SELECT EXTEND_INFO, FILE_NAME FROM ATTACHMENT WHERE ID = '%@'", fileinfosDic[@"fileId"]];
        FMResultSet *result = [db executeQuery:sql];
        
        while ([result next]) {
            NSString *extendInfo = [result stringForColumn:@"EXTEND_INFO"];
            NSString *fileName = [result stringForColumn:@"FILE_NAME"];
            NSDictionary *dic = @{@"extendInfo":extendInfo, @"fileName":fileName};
            [AttArr addObject:dic];
        }
    }
    [db close];
    return AttArr;
}


// 查找图片路径
- (void)getImagePath:(NSArray *)array {
    for (int i = 0; i < array.count; i++) {
        NSDictionary *dic = array[i];
        NSString *fileNameStr = dic[@"fileName"];
        NSString *imagePath = [LSUtility getImagePath:fileNameStr];
        [self.selectedAssetURLs addObject:imagePath];
    }
    self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
}


//创建右上角审阅按钮
- (void)cteateRightItem{
    
    UIButton *btn_1=[[UIButton alloc]initWithFrame:CGRECTS(0, 0, 40, 20)];
    btn_1.backgroundColor=[UIColor whiteColor];
    [btn_1 setTitle:@"合格" forState:UIControlStateNormal];
    btn_1.layer.cornerRadius=3.;
    btn_1.tag=100;
    btn_1.titleLabel.font=[UIFont systemFontOfSize:11.];
    [btn_1 setTitleColor:[UIColor colorWithRed:0.29 green:0.68 blue:0.64 alpha:1.00] forState:UIControlStateNormal];
    [btn_1 addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *btn_2=[[UIButton alloc]initWithFrame:CGRECTS(0, 0, 40, 20)];
    btn_2.tag=101;
    btn_2.backgroundColor=[UIColor whiteColor];
    btn_2.titleLabel.font=[UIFont systemFontOfSize:11.];
    btn_2.layer.cornerRadius=3.;
    [btn_2 setTitle:@"不合格" forState:UIControlStateNormal];
    [btn_2 setTitleColor:[UIColor colorWithRed:0.75 green:0.19 blue:0.23 alpha:1.00] forState:UIControlStateNormal];
    [btn_2 addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *bar_Btn_1=[[UIBarButtonItem alloc]initWithCustomView:btn_1];
    UIBarButtonItem *bar_Btn_2=[[UIBarButtonItem alloc]initWithCustomView:btn_2];
    
    self.navigationItem.rightBarButtonItems=@[bar_Btn_2,bar_Btn_1];
}



#pragma mark -methlod
- (void)clickAction:(UIButton *)sender{
    if(sender.tag==100){
        //合格
        _qualified = 5;
        self.reviewState = REVIEW_STATE_PASS_YES;
        [self showAlert];
        
    } else if(sender.tag==101){
        //不合格
        _qualified = 402;
        self.reviewState = REVIEW_STATE_PASS_NO;
        [self showAlert];
        
    } else if(sender.tag==102){
        
        if (self.content && ![self.content isEqualToString:@""]) {
            //提交
            [alert hide];
            [self reView];
            
        } else {
            [LSUtility showToastWithMessage:@"请输入说明" inView:self.navigationController.view Andtime:1.];
        }

    } else{
        //关闭审阅
        [alert hide];
    }
}
- (void)showAlert{
    
    alert = [[FDAlertView alloc] init];
    AlertVIew *contentView=[[AlertVIew alloc]initWithFrame:CGRECTS(0, 0, 300, 200)];
    
    contentView.textViewBlock=^(NSString *value){
        self.content = value;
        NSLog(@"%@",self.content);
    };
    
    //提交btn
    UIButton *submitBtn= contentView.submit;
    submitBtn.tag=102;
    [submitBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //关闭btn
    UIButton *closeBtn= contentView.closeBtn;
    closeBtn.tag=103;
    [closeBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //添加到alert
    alert.contentView = contentView;
    
    [alert show:self.view];
}

#pragma mark- 审阅
- (void)reView {
    // 修改流程
    [self editFlow];
    
    // 添加流程记录
    [self addFlowRecordData];
    
    // 通知列表页刷新数据
    [[NSNotificationCenter defaultCenter] postNotificationName:@"checkYS" object:nil];
    // 通知首页刷新数据
    [[NSNotificationCenter defaultCenter] postNotificationName:@"home" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 修改流程
- (void)editFlow {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    // 修改流程
    NSString *sqlStr2=[NSString stringWithFormat:@"UPDATE PROCESS SET PROCESS_STAGE = '%i', LOCAL_MODIFY_STATE = 'MOD', RECIFY_REVIEW_USERS = '%@', MODIFY_USER_NAME = '%@', MODIFY_IP = '%@', MODIFY_TIME = '%@' WHERE ID = '%@'",_qualified, USERID, DEF_PERSISTENT_GET_OBJECT(@"realname"), [LSUtility getIPAddress], [LSUtility nowTime], self.processId];
    if([db executeUpdate:sqlStr2]){
        NSLog(@"修改成功");
    }else{
        NSLog(@"修改失败");
    }
    [db close];
}


#pragma mark - 新增数据(流程记录表)
- (void)addFlowRecordData {
    ProcessRecordModel *model=self.dataArray[0];
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    DBHelper *dbhelper=[DBHelper help];
    //字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    pragameDic=@{
                 @"ID":[NSUUID UUID].UUIDString,
                 @"PRO_ID":DEFISNUL(model.PRO_ID),
                 @"PROCESS_ID":DEFISNUL(self.processId),
                 @"WEATHER":DEFISNUL(model.WEATHER),
                 @"ADDRESS_ID":DEFISNUL(model.ADDRESS_ID),
                 @"ADDRES_INFO":DEFISNUL(model.ADDRES_INFO),
                 @"PROCESS_TYPE":[NSString stringWithFormat:@"%ld", (long)model.PROCESS_TYPE],
                 @"PROCESS_STAGE":[NSString stringWithFormat:@"%d", _qualified],
                 @"RECORD_USER":USERID,
                 @"PROBLEM_TYPE":[NSString stringWithFormat:@"%ld", (long)model.PROBLEM_TYPE],
                 @"RECORD_MASTER":DEFISNUL(model.RECORD_MASTER),
                 @"RECIFY_USER":DEFISNUL(model.RECIFY_USER),
                 @"RECIFY_UNIT":DEFISNUL(model.RECIFY_UNIT),
                 @"SEVERITY":DEFISNUL(model.SEVERITY),
                 @"END_TIME":DEFISNUL(model.END_TIME),
                 @"SEND_TIME":[LSUtility nowTime],
                 @"SEND_TYPE":DEFISNUL(model.SEND_TIME),
                 @"PROCESS_TITLE":DEFISNUL(model.PROCESS_TITLE),
                 @"PROCESS_CONTENT":DEFISNUL(model.PROCESS_CONTENT),
                 @"PROCESS_REQUIRED":DEFISNUL(model.PROCESS_REQUIRED),
                 @"PROCESS_DESC":DEFISNUL(model.PROCESS_DESC),
                 @"SUBMITTORS":DEFISNUL(model.SUBMITTORS),
                 @"PUT_USER":DEFISNUL(model.PUT_USER),
                 @"REVIEW_USER":USERID,
                 @"REVIEW_OPINION":DEFISNUL(self.content),
                 @"REVIEW_STATE":[NSString stringWithFormat:@"%d", self.reviewState],
                 @"FILEINFOS":DEFISNUL(model.FILEINFOS),
                 @"EXTEND_INFO":DEFISNUL(model.EXTEND_INFO),
                 @"CREATE_USER_NAME":USERID,
                 @"CREATE_TIME":[LSUtility nowTime],
                 @"CREATE_IP":[LSUtility getIPAddress],
                 @"MODIFY_USER_NAME":USERID,
                 @"MODIFY_IP":[LSUtility getIPAddress],
                 @"MODIFY_TIME":[LSUtility nowTime],
                 @"LOCAL_MODIFY_USER_NAME":USERID,
                 @"LOCAL_MODIFY_TIME":[LSUtility nowTime],
                 @"LOCAL_MODIFY_STATE":@"ADD",
                 };
    if (!pragameDic) {
        return;
    }
    BOOL isAdd=[dbhelper DataBase:db insertKeyValues:pragameDic intoTable:PROCESS_RECORD];
    if(isAdd){
        NSLog(@"验收记录新增成功");
    }else{
        NSLog(@"验收记录新增失败");
    }
    [db close];
}

#pragma mark- UITaleViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    long section=indexPath.section;
    long row=indexPath.row;
    if(section==0){
        return 44;
    }else if(section==1){
        if(row==0){
            return 44;
        }else{
            return 120;
        }
    }else if (section == 2) {
        if (![self.pRecordModel.PROCESS_DESC isEqualToString:@""]) {
            NSArray *descArr = [self.pRecordModel.PROCESS_DESC componentsSeparatedByString:@"/"];
            CGFloat margin = 5;
            CGFloat H = 15;
            return descArr.count * (margin + H) + 25;
        } else {
            return 25;
        }
    } else {
        return [H1_ImagesCell cellHeightWithObj:_curTweet title:@"图片"];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0 || section == 3){
        return 0.001;
    }else{
        return 10;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0){
        return 7;
    }else if (section==1){
        return 3;
    }else{
        return 1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //组
    long section=indexPath.section;
    //行
    long row=indexPath.row;
    ProcessRecordModel *rmodel = self.dataArray[0];
    
    if(section==0){
        if(row==0){
            TableTopStateCell *cell=[tableView dequeueReusableCellWithIdentifier:@"topCell" forIndexPath:indexPath];
            cell.title.text=[NSString stringWithFormat:@"%@  验收审阅",rmodel.CREATE_DATE];
            return cell;
        }else{
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"fCell" forIndexPath:indexPath];
            if(row==1){
                NSString *proName=[LSUtility getProjectNameByProjectId:rmodel.PRO_ID][@"PROJECT_NAME"];
                [cell setTitle:@"项  目:" andDetail:proName];
            }else if (row==2){
                NSDictionary *addressInfoDic = [LSUtility dictionaryWithJsonString:self.addInfo];
                
                NSString *rmodel = [NSString stringWithFormat:@"%@ %@",
                                    DEFISNUL(addressInfoDic[@"address"]),
                                    DEFISNUL(addressInfoDic[@"leftDistanceStr"])];
                [cell setTitle:@"位  置:" andDetail:rmodel];
            }else if (row==3){
                [cell setTitle:@"监  理:" andDetail:
                 [LSUtility getuserIdByUserName:USERID][@"REAL_NAME"]];
            }else if (row==4){
                NSString *name=[LSUtility getuserIdByUserName:rmodel.PUT_USER][@"REAL_NAME"];
                [cell setTitle:@"报送人:" andDetail:name];
            }else if (row==5){
                [cell setTitle:@"编  号:" andDetail:self.processNumber];
            }else{
                [cell setTitle:@"时  间:" andDetail:rmodel.CREATE_TIME];
            }
            return cell;
        }
    }else if(section==1){
        if(row==0){
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"fCell" forIndexPath:indexPath];
            [cell setTitle:@"标  题:" andDetail:rmodel.PROCESS_TITLE];
            return cell;
        }else{
            B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"tCell" forIndexPath:indexPath];
            cell.isEdit=NO;
            if(row==1){
                cell.title.text = @"内  容:";
                cell.text.text = rmodel.PROCESS_CONTENT;
                return cell;
            }else{
                cell.title.text=@"意  见:";
                cell.text.placeholder = @"";
                cell.text.text= rmodel.REVIEW_OPINION;
                return cell;
            }
        }
    } else if(section == 2) {
        
        AttachmentMessageCell *cell = [[AttachmentMessageCell alloc] initWithReuseIdentifier:@"amCell" withModel:rmodel];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
        
    } else {
        H1_ImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:@"photoCell" forIndexPath:indexPath];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.isEdit = NO;
        cell.curTweet = _curTweet;
        return cell;
    }
}


@end
